package com.example.compose.ui.dialog

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.example.compose.App
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking


@SuppressLint("PermissionLaunchedDuringComposition")
@ExperimentalPermissionsApi
@Composable
fun FeatureThatRequiresPermission(
    permissions:MutableList<String> = mutableListOf(android.Manifest.permission.CAMERA),
    firstContent:String = "该权限这个应用程序很重要，请授予权限。",
    secondRequest:String = "需要该权限才能使用此功能，请授予权限。",
    lifecycle:Lifecycle,
    onSuccess: () -> Unit,
    onFail: () -> Unit,
) {
    val multiplePermissionsState = rememberMultiplePermissionsState(permissions)
    //权限是否"拒绝且不在访问"
    val isDenied = remember { mutableStateOf(false)}
    //是否在进行请求
    var isRequest = false
    //进行请求前shouldShowRationale状态
    var resumeShouldShowRationale = false

    class AppLifeObserver: LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event){
                Lifecycle.Event.ON_RESUME -> if(isRequest){
                    isDenied.value = resumeShouldShowRationale == multiplePermissionsState.shouldShowRationale
                    isRequest = false
                }
                else -> {}
            }
        }
    }

    lifecycle.addObserver(AppLifeObserver())

    when (multiplePermissionsState.allPermissionsGranted) {
        true -> {
            onSuccess()
        }
        false -> {
            Dialog(onDismissRequest = {}) {
                var textToShow =""
                var textToTip =""
                var textToGo =""
                resumeShouldShowRationale = multiplePermissionsState.shouldShowRationale
                if(isDenied.value){
                    textToShow = secondRequest
                    textToTip = "取消前往"
                    textToGo = "前往设置"
                }
                else if ( resumeShouldShowRationale) {
                    textToShow = firstContent
                    textToTip = "取消许可"
                    textToGo = "请求许可"
                }else {
                    runBlocking {
                        launch {
                            delay(100)
                            multiplePermissionsState.launchMultiplePermissionRequest()
                            isRequest = true
                        }
                    }

                }
                Column(
                    horizontalAlignment=Alignment.CenterHorizontally,
                    modifier = Modifier
                        .fillMaxWidth().height(120.dp)
                        .clip(RoundedCornerShape(5.dp))
                        .background(Color.hsv(0f, 0f, 1f, if(textToShow=="") 0f else 0.3f))
                        .padding(25.dp, 5.dp)
                ) {
                    Text(textToShow, color = Color.White, modifier = Modifier.padding(10.dp))
                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
                        Box(modifier = Modifier.fillMaxWidth(0.5f), contentAlignment = Alignment.CenterStart) {
                            TextButton(
                                onClick = {
                                    onFail()
                                }) {
                                Text(textToTip, color = Color.White)
                            }
                        }
                        Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
                            TextButton(
                                onClick = {
                                    if(isDenied.value) {
                                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                        intent.data = Uri.fromParts("package", App().getContext().packageName, null)
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                        App().getContext().startActivity(intent)
                                        //为了跳转设置时回来重新检查权限
                                        resumeShouldShowRationale = true
                                    }
                                    else {
                                        multiplePermissionsState.launchMultiplePermissionRequest()
                                    }
                                    isRequest = true
                                }) {
                                Text( text = textToGo , color = Color.Red)
                            }
                        }
                    }
                }
            }
        }
    }
}
